package com.pj.ca.service.impl;

import com.pj.ca.service.AsymmetricalCipher;
import com.pj.ca.service.AsymmetricalSignature;
import com.pj.ca.sm.impl.Sm2PrivateKeyImpl;
import com.pj.ca.sm.impl.Sm2PublicKeyImpl;
import com.pj.ca.util.AsymmetricalUtil;
import com.pj.ca.util.Sm2Util;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * 描述：
 *
 * @author pengjun
 * @date 2021/11/3 10:54
 */
public class SM2 implements AsymmetricalCipher, AsymmetricalSignature {
    @Override
    public byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
        return Sm2Util.encrypt( new Sm2PublicKeyImpl((BCECPublicKey) publicKey), data);

    }

    @Override
    public byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
        return Sm2Util.decrypt(new Sm2PrivateKeyImpl((BCECPrivateKey) privateKey), data);
    }

    @Override
    public byte[] sign(byte[] data, PrivateKey privateKey, String signAlgorithm) throws Exception {
        Signature signature = AsymmetricalUtil.getSignatureInstance(signAlgorithm);
        signature.initSign(privateKey);
        signature.update(data);
        return signature.sign();
    }

    @Override
    public boolean verifySign(byte[] signData, byte[] content, PublicKey publicKey, String signAlgorithm) throws Exception {
        Signature signature = AsymmetricalUtil.getSignatureInstance(signAlgorithm);
        signature.initVerify(publicKey);
        signature.update(content);
        return signature.verify(signData);
    }
}
